//
//  CDViewController.m
//  SugarPile
//
//  Created by LC on 16/2/29.
//  Copyright © 2016年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "CDViewController.h"
#import "LCPrefixHeader.pch"
#import "DvdDetalisModel.h"
#import "CDCollectionReusableView.h"
#import "CDModel.h"
#import "CDCollectionViewCell.h"
#import "HotDetailsViewController.h"
#import "UserViewController.h"
#import "DvdDetailsViewController.h"
static int i = 0;

@interface CDViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, LCLayoutItemHeightDelegate, userPushDelegate, pushAlbumDelegate, pushYongHuDelegate>
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *dataArr;
@property (nonatomic, copy)NSString *url_str;//网络请求的网址
@property (nonatomic, assign)NSInteger count;//给data数组中添加 数据 的个数
@property (nonatomic, retain)NSNumber *next_start;//实际能请求的 数据 个数
@property (nonatomic, retain)NSNumber *maxCount;//数据的 总个数
@property (nonatomic, retain)NSNumber *more;//更多的个数
@property (nonatomic, retain)NSNumber *userId; /**< 记录传值的用户ID */
@property (nonatomic, retain)NSNumber *dvdId; /**< 记录传值的专辑ID */

@end

@implementation CDViewController
-(void)dealloc
{
    [_ID release];
    [_cdCount release];
    [_dataArr release];
    [_collectionView release];
    [_dataArr release];
    [_url_str release];
    [_next_start release];
    [_maxCount release];
    [_more release];
    [_userId release];
    [_dvdId release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (i == 0) {
        self.more = @(1);
        i++;
    }



    // 数据解析
    [self dataArrHandle];
    
//    // 创建Collection
    [self createCollection];

}
- (void)createCollection
{
    
    //自定义layout
    LClayout *layout = [[LClayout alloc] init];
    //layout的count为2 两列
    layout.columcounts = 2;
    //layout 的 列间距
    layout.columSpace = 10;
    //layout 的 行间距
    layout.rowSpace = 10;
    //layout的边距
    layout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    
    
    //初始化 collection
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:layout];
    //    [layout release];
    //设置collection的背景颜色
    _collectionView.backgroundColor = [UIColor floralWhite];
    //签协议
    layout.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    [self.view addSubview:_collectionView];
    _collectionView.contentInset = UIEdgeInsetsMake(150, 0, 0, 0);
    CDCollectionReusableView *headView = [[CDCollectionReusableView alloc] initWithFrame:CGRectMake(0, -150, WIDTH, 150)];
    headView.dic = _dataDic;
    headView.delegate = self;
    [self.collectionView addSubview:headView];
    //把collection添加进视图
    //注册重用池 为cell
    [_collectionView registerClass:[CDCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [layout release];
    [_collectionView release];
}
- (void)dataArrHandle
{
    NSString *url = @"http://203.80.144.212/napi/blog/list/by_album/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count%2Ctop_comments%2Ctop_like_users&platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=69&start=0&album_id=76646519&platform_name=Android&locale=zh&app_code=nayutas";
    [LCAFNetWorking GETWithURL:[url stringByReplacingOccurrencesOfString:@"76646519" withString:_ID.stringValue]  completion:^(id result) {
        
        NSArray *arr = result[@"data"][@"object_list"];
        self.next_start = result[@"data"][@"next_start"];
        self.more = result[@"data"][@"more"];
        _count += 24;
        self.dataArr = [CDModel modelHanderWithArray:arr];
        
        [_collectionView reloadData];        // 刷新
       
    }];

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    //创建cell
    CDCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //创建model
    if (_dataArr.count != 0) {
        CDModel *m = _dataArr[indexPath.item];
        //把 model 传递给 cell
        cell.model = m;
        cell.delegate = self;
        cell.albumDelegate = self;
        // 赋值
        self.userId = m.senderId;
    }
    return cell;
}

- (CGFloat)layout:(LClayout *)layout heightForItemAtindexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    //计算图片的高度
    //tw/th = iw/ih
    if (_dataArr.count != 0) {
        CDModel *m = _dataArr[indexPath.item];
        //图片高度
        CGFloat imgH = width * m.height.doubleValue / m.width.doubleValue;
       
        
        //文本高度
        CGFloat textHeight = [CDCollectionViewCell heightWithText:m.msg];
        //判断文本框 高度是否 超过 15.51 * 6 的 高度(6行的高度)
        if (textHeight >= 15.51 * 6) {
            //设置最大文本框行数 为 6行;
            textHeight = 15.51 * 6;
        }
        //    NSLog(@"%@      ======     %f  ~~~~ %f", m.msg, imgH, textHeight);
        // 每个cell的高度 由 图片高度 和 文本高度  + 其他控件高度(80)
        return imgH + textHeight + 80;
    }
    return 0;
}
#pragma mark -点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSLog(@"indexPath:%ld", (long)indexPath.row);
    //创建 对象
    HotDetailsViewController *hotVC = [[[HotDetailsViewController alloc] init] autorelease];
    CDModel *m = _dataArr[indexPath.item];
    //把ID 传递给 下一页 的 接口
    hotVC.detailsId = m.ID;
    [self.navigationController pushViewController:hotVC animated:YES];
 
}

- (void)array:(NSMutableArray *)arr
{
    
}
#pragma mark - push用户界面(协议方法)
- (void)pushYongHu:(NSString *)str
{

    
    UserViewController *userVC = [[[UserViewController alloc] init]autorelease];
 
    
    NSString *url = @"http://203.80.144.213/napi/people/profile/?include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&platform_version=4.4.4&device_platform=HM%2B2A&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=69&_ts=1456832673350&platform_name=Android&locale=zh&app_code=nayutas&user_id=6645294";
    [LCAFNetWorking GETWithURL:[url stringByReplacingOccurrencesOfString:@"6645294" withString:[NSString stringWithFormat:@"%@", _userId]]  completion:^(id result) {
        // 处理好的专辑头字典传入第二页
        userVC.user_id = _userId;
        userVC.dic = result[@"data"];
        // 跳转
        [self.navigationController pushViewController:userVC animated:YES];
        
    }];

    
}

#pragma mark - push专辑页 (协议方法)
- (void)pushAlbum:(NSString *)str maxCount:(NSNumber *)count
{
    NSLog(@"sss");
    CDViewController *cdVC = [[[CDViewController alloc] init] autorelease];
    cdVC.ID = _ID;
    cdVC.dataDic = _dataDic;
    [self.navigationController pushViewController:cdVC animated:YES];
    
}
- (void)userPushAction:(NSString *)str userDic:(NSDictionary *)dictionary
{
    UserViewController *userVC = [[[UserViewController alloc] init] autorelease];

    // 字符串转NSNumber
    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    id userId = [f numberFromString:str];
    
    
    NSString *url = @"http://203.80.144.213/napi/people/profile/?include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&platform_version=4.4.4&device_platform=HM%2B2A&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=69&_ts=1456832673350&platform_name=Android&locale=zh&app_code=nayutas&user_id=6645294";
    [LCAFNetWorking GETWithURL:[url stringByReplacingOccurrencesOfString:@"6645294" withString:[NSString stringWithFormat:@"%@", userId]]  completion:^(id result) {
        
        // 处理好的专辑头字典传入第二页
        userVC.user_id = userId;
        userVC.dic = result[@"data"];
        // 跳转
        [self.navigationController pushViewController:userVC animated:YES];
        
    }];

}

#pragma mark - bolck传值
- (void)userAction:(UITapGestureRecognizer *)tap
{
    CDCollectionReusableView *cdVC = [[[CDCollectionReusableView alloc] init] autorelease];
    
     __weak CDViewController *vc = self;
    void (^changeStr)(NSString *) = ^(NSString *str){
        vc.str = str;
    };
    // 把遥控器传值给第二页
    cdVC.textBlock = changeStr;
    [self.navigationController pushViewController:cdVC animated:YES];
    
//    NSString *userTemp = @"http://www.duitang.com/napi/people/profile/?__dtac=%257B%2522_r%2522%253A%2520%2522998121%2522%257D&_ts=1452865118.002704&app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&include_fields=relationship%2Cbind_status%2Cinterests%2Cidentity%2Ccity%2Ccitycode%2Cgender%2Cbirthday%2Crecommend_info%2Cclub_count&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320&user_id=11200118";
//    NSString *userStr = [userTemp stringByReplacingOccurrencesOfString:@"11200118" withString:[_dic[@"user"][@"id"] stringValue]];
//    //    NSLog(@"%@", userStr);
//    //AFN网络请求
//    AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
//    [userData GET:userStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        nil;
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        //        NSLog(@"%@", responseObject);
//        NSMutableDictionary *userDic = responseObject[@"data"];
//        [self.delegate userPushAction:[_dic[@"user"][@"id"] stringValue] userDic:userDic];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        nil;
//    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
